package com.gbase8c.dmt.dao.file;

import com.gbase8c.dmt.config.DmtConfig;
import com.gbase8c.dmt.dao.SnapshotDao;
import com.gbase8c.dmt.model.migration.config.Snapshot;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.List;
import java.util.stream.Collectors;

public class SnapshotDaoImpl extends BasicDao<Snapshot> implements SnapshotDao {

    private DmtConfig dmtConfig;

    public SnapshotDaoImpl(DmtConfig dmtConfig) {
        super();
        this.dmtConfig = dmtConfig;
        mkdirs(path());
    }

    @Override
    public String path() {
        return dmtConfig.taskDir() + File.separator + "snapshot";
    }

    @Override
    public File file(Snapshot snapshot) {
        String filepath = StringUtils.join(new String[] {path(), snapshot.getId() + ".json"}, File.separator);
        return new File(filepath);
    }

    @Override
    public void preSave(String id, Snapshot snapshot) {
        snapshot.setId(id);
    }

    @Override
    public List<Snapshot> list(String dsId) {
        List<Snapshot> snapshots = super.list();
        return snapshots.stream()
                .filter(snapshot -> snapshot.getDsId().equalsIgnoreCase(dsId))
                .collect(Collectors.toList());
    }

    @Override
    public void delete(Snapshot snapshot) {
        delete(snapshot.getId());
    }

}
